<template>
    <div class="profitIncentiveHandle">

        <el-breadcrumb separator="/" class="bread-title">
            <el-breadcrumb-item :to="{ path: '/profitIncentive' }">利润结算标准</el-breadcrumb-item>
            <el-breadcrumb-item>{{typeMap[type]}}</el-breadcrumb-item>
        </el-breadcrumb>


        <div v-if="type==='view'">
            <div>提取标准: {{extractStandard[currentStandard.extractStandard]}}</div>
            <div class="mt50 mb20">计提分配标准</div>
            <div>集团管理计提比例：{{currentStandard.groupProportion}}%</div>
            <div class="mt20 mb20">好生活应发占比：{{currentStandard.easylifeProportion}}%</div>
            <div>好生活部门应发占比：</div>
            <el-table
                    :data="currentStandard.departSettingList"
                    border
                    style="width: 500px;margin-top: 20px">
                <el-table-column
                        type="index"
                        label="序号"
                        align="center"
                        width="50">
                </el-table-column>
                <el-table-column
                        prop="departmentName"
                        align="center"
                        label="部门">
                </el-table-column>
                <el-table-column
                        align="center"
                        label="分配比例（%）">
                    <template slot-scope="scope">{{scope.row.departmentProportion}}%</template>
                </el-table-column>
            </el-table>
        </div>
        <div v-else>
            <div v-if="stepIndex === 0 ">
                <h3>请选择标准类型</h3>
                <hr/>
                <el-button class="mt20" type="primary" icon="el-icon-plus" @click="selectDialog(true)">选择标准</el-button>

                <div class="selectedType" v-if="currentStandard.id">
                    <div>提取标准：{{extractStandard[currentStandard.extractStandard]}}</div>
                    <div>佣金来源：{{commSource[currentStandard.commSource]}}</div>
                    <div>提取规则：{{extractCategory[currentStandard.extractCategory]}}</div>
                    <div>计提方式：{{extractType[currentStandard.extractType]}}</div>
                    <div>版 &nbsp; &nbsp; &nbsp; 本：{{currentStandard.version}}</div>
                </div>

                <div class="mt50">
                    <el-button class="mt20" @click="returnList">取消</el-button>
                    <el-button class="mt20" type="primary" @click="changeStepIndex(1)">下一步</el-button>
                </div>

                <el-dialog
                        title="选择区间标准"
                        :visible.sync="selectDialogVisible"
                        width="40%">
                    <div>
                        <el-row :span="24" :gutter="20">
                            <el-col :span="18">
                                <el-input
                                        placeholder="请输入内容"
                                        prefix-icon="el-icon-search"
                                        size="normal"
                                        v-model="selectDialogInputValue">
                                </el-input>
                            </el-col>
                            <el-col :span="6">
                                <el-button size="normal" type="primary" @click="getSettleListByPage">查询</el-button>
                            </el-col>
                        </el-row>

                        <div class="mt20" style="height: 300px; overflow: auto">
                            <div class="selectedInterval-item" v-for="item in dialogList">
                                <el-radio v-model="selectedInterval" :label="item.id">
                                    <div>提取标准：{{extractStandard[item.extractStandard]}}</div>
                                    <div>佣金来源：{{commSource[item.commSource]}}</div>
                                    <div>提取规则：{{extractCategory[item.extractCategory]}}</div>
                                    <div>计提方式：{{extractType[item.extractType]}}</div>
                                    <div>版 &nbsp; &nbsp; &nbsp; 本：{{item.version}}</div>
                                </el-radio>
                            </div>
                        </div>
                    </div>
                    <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="selectDialog(false)">选 择</el-button>
                <el-button @click="selectDialogVisible = false">取 消</el-button>
            </span>
                </el-dialog>
            </div>
            <div v-else>
                <div>
                    <h4>集团管理计提比例</h4>
                    <el-input class="w200 mr10" size="mini" v-model="currentStandard.groupProportion" @input="checkGroupProportion(currentStandard.groupProportion)"></el-input>
                    %
                </div>
                <hr class="mt20 mb20"/>
                <div class="mt20">
                    <h3>部门应发占比</h3>
                    <el-button class="mb20" type="primary" @click="selectDepartment(true)">选择分配部门</el-button>
                    <el-table
                            :data="currentStandard.departSettingList"
                            border
                            style="width: 100%">
                        <el-table-column
                                type="index"
                                label="序号"
                                align="center"
                                width="80">
                        </el-table-column>
                        <el-table-column
                                prop="departmentName"
                                align="center"
                                label="部门">
                        </el-table-column>
                        <el-table-column
                                align="center"
                                label="分配比例（%）">
                            <template slot-scope="scope">
                                <el-input size="mini" v-model="scope.row.departmentProportion" @input="checkProportion(scope.row.departmentProportion, scope.$index)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column
                                label="操作">
                            <template slot-scope="scope">
                                <a href="javascript:;;" @click="delDepartmentProportion(scope.$index)">删除</a>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <div class="mt50">
                    <el-button class="mt20" @click="changeStepIndex(0)">上一步</el-button>
                    <el-button class="mt20" type="primary" @click="save">保存</el-button>
                </div>
                <el-dialog
                        title="添加部门"
                        :visible.sync="departmentDialogVisible"
                        width="550px"
                >
                    <el-transfer
                            filterable
                            filter-placeholder="请输入部门名称"
                            :titles="['全部部门', '已选中']"
                            v-model="department"
                            :props="{
                           key: 'id',
                           label: 'departmentName'
                        }"
                            :data="departmentList">
                    </el-transfer>
                    <span slot="footer" class="dialog-footer">
                    <el-button @click="departmentDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="selectedDepartment">确 定</el-button>
                </span>
                </el-dialog>
            </div>
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
    import api from '@/api/apiPath'
    import {extractStandard, commSource, extractType, extractCategory} from '../fieldMap'

    export default {
        name: 'profitIncentiveHandle',
        data() {
            return {
                type: "new",
                typeMap: {
                    new: '新建',
                    edit: '编辑',
                    view: '查看'
                },

                stepIndex: 0,
                selectDialogVisible: false,
                selectDialogInputValue: "",
                selectedInterval: "",

                dialogList: [],
                departmentDialogVisible: false,
                department: [],
                departmentList: [],
                departmentListMap: [],
                pcTableData: [],
                extractStandard, commSource, extractType, extractCategory,
                currentStandard: {}
            }
        },
        created() {
            this.getAllDepartmentList();
            this.type = this.$route.query.type;
            if (this.type !== 'new') {
                this.viewProdrawStandard(this.$route.query.id)
            }
        },
        mounted() {

        },
        methods: {
            returnList() {
                this.$router.push({path: "./profitIncentive"})
            },
            getAllDepartmentList() {
                this.axios.post(api.getAllDepartmentList, {}).then((res) => {
                    let departmentListMap = {};
                    this.departmentList = res.data.data;
                    this.departmentList.forEach((item) => {
                        departmentListMap[item.id] = item.departmentName
                    })
                    this.departmentListMap = departmentListMap;
                })
            },
            selectDialog(flag) {
                this.selectDialogVisible = flag;
                if (flag) {
                    this.getSettleListByPage()
                }
                if (!flag && this.selectedInterval) {
                    this.currentStandard = this.dialogList.find((value) => {
                        return value.id === this.selectedInterval
                    });
                }
            },
            changeStepIndex(index) {
                if (index === 1 && !this.currentStandard.id) {
                    this.$message({
                        message: '请选择标准！',
                        type: 'warning'
                    });
                    return false;
                }
                this.stepIndex = index;
            },
            selectDepartment(type) {
                this.departmentDialogVisible = type;
                if (type) {
                    // 清空选中值
                    this.department = [];

                    if (this.currentStandard.departSettingList && this.currentStandard.departSettingList.length) {
                        let selectArr = []
                        this.currentStandard.departSettingList.forEach((item) => {
                            selectArr.push(item.departmentId);
                        })
                        this.departmentList.forEach((item, index) => {
                            this.$set(this.departmentList[index], 'disabled', selectArr.indexOf(item.id) > -1)
                        })
                    } else {
                        this.currentStandard.departSettingList = [];
                        this.departmentList.forEach((item, index) => {
                            this.$set(this.departmentList[index], 'disabled', false)
                        })
                    }
                }

            },

            selectedDepartment() {
                console.log("选择的部门", this.department);
                if(this.department.length === 0){
                    this.$message({
                        message: '请选择部门！',
                        type: 'warning'
                    });
                    return false;
                }


                this.department.forEach((item) => {
                    this.currentStandard.departSettingList.push({
                        departmentId: item,
                        departmentName: this.departmentListMap[item],
                        departmentProportion: "",
                    })
                })
                this.departmentDialogVisible = false;
            },
            delDepartmentProportion(index) {
                this.currentStandard.departSettingList.splice(index, 1)
            },
            replaceNum(value) {
                value = value.replace(/[^\d.]/g, '');
                value = value.replace(/\.{2,}/g, ".");
                value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
                value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
                if (value.indexOf('.') < 0 && value != '') {
                    value = parseInt(value);
                }
                return value
            },
            checkGroupProportion(value) {
                value = this.replaceNum(value);
                setTimeout(() => {
                    this.$set(this.currentStandard, 'groupProportion', value)
                }, 30)
            },
            checkProportion(value, subIndex) {
                value = this.replaceNum(value);
                setTimeout(() => {
                    this.$set(this.currentStandard.departSettingList[subIndex], 'departmentProportion', value)
                }, 30)
            },
            getSettleListByPage() {
                this.axios.post(api.getSettleListByPage, {
                    version: this.selectDialogInputValue
                }).then((res) => {
                    this.dialogList = res.data.data.list;
                })
            },
            save() {
                if (this.currentStandard.groupProportion) {
                    if (this.currentStandard.groupProportion >= 100 || this.currentStandard.groupProportion <= 0) {
                        this.$message({
                            message: '集团计提比例必须大于0小于100！',
                            type: 'warning'
                        });
                        return false;
                    }
                } else {
                    this.$message({
                        message: '集团计提比例不能为0或空！',
                        type: 'warning'
                    });
                    return false;
                }
                if (!this.currentStandard.departSettingList || this.currentStandard.departSettingList.length === 0) {
                    this.$message({
                        message: '请至少选择一个部门！',
                        type: 'warning'
                    });
                    return false;
                }

                let count = 0;
                let departmentList = []
                this.currentStandard.departSettingList.forEach((item) => {
                    console.log(item);
                    count += +item.departmentProportion
                    departmentList.push({
                        departmentId: item.departmentId,
                        departmentName: item.departmentName,
                        departmentProportion: item.departmentProportion,
                    })
                })

                if (count !== 100) {
                    this.$message({
                        message: '部门计提比例之和必须为100%！',
                        type: 'warning'
                    });
                    return false;
                }

                this.axios.post(api.createProdrawStandard, {
                    standardId: this.currentStandard.id,
                    groupProportion: this.currentStandard.groupProportion,
                    departmentList: departmentList
                }).then((res) => {
                    if(res.data.code === 200){
                        this.$message({
                            message: this.typeMap[this.type] + "成功",
                            type: 'success'
                        });
                        this.returnList();
                    }
                })
            },

            viewProdrawStandard(id) {
                let currentStandard = {}
                this.axios.post(api.viewProdrawStandard, {
                    standardId: id
                }).then((res) => {
                    currentStandard = res.data.data;
                    return this.axios.post(api.getSettleListByPage, {
                        standardId: currentStandard.standardId
                    })
                }).then((res) => {
                    let departSettingList = [];
                    currentStandard.departmentList.forEach((item) => {
                        departSettingList.push({
                            departmentId: item.departmentId,
                            departmentProportion: item.departmentProportion,
                            departmentName: this.departmentListMap[item.departmentId]
                        })
                    })
                    this.currentStandard = res.data.data.list[0]
                    this.$set(this.currentStandard, 'groupProportion', currentStandard.groupProportion)
                    this.currentStandard.easylifeProportion = currentStandard.easylifeProportion;
                    this.currentStandard.departSettingList = departSettingList;
                })
            }
        },
        components: {},
        computed: {}
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus">
    .selectedInterval-item {
        padding: 0 20px;
        label {
            display: flex;
            align-items: center;
            > span {
                display: inline-block;
                margin-top: 20px;
                > div {
                    margin: 10px 0;
                }
            }
        }
        .selectedInterval-item-row {
            line-height: 25px;
        }
    }

    .selectedType {
        padding: 20px;
        margin: 20px 0;
        border: 1px solid #ccc;
        width: 200px;
        div {
            margin: 5px 0;
        }
    }
</style>
